import { BrowserWindow, shell } from 'electron'
import { join } from 'path'
import { MAIN_WINDOW_CONFIG, LOGIN_WINDOW_CONFIG } from '../shared/constants'
import { logger } from '@roasmax/logger'

export class WindowManager {
  private mainWindow: BrowserWindow | null = null
  private loginWindow: BrowserWindow | null = null

  /**
   * 创建主窗口
   */
  createMainWindow(): BrowserWindow {
    if (this.mainWindow && !this.mainWindow.isDestroyed()) {
      this.mainWindow.focus()
      return this.mainWindow
    }

    const icon = this.getAppIcon()
    this.mainWindow = new BrowserWindow({
      width: MAIN_WINDOW_CONFIG.width,
      height: MAIN_WINDOW_CONFIG.height,
      minWidth: MAIN_WINDOW_CONFIG.minWidth,
      minHeight: MAIN_WINDOW_CONFIG.minHeight,
      show: false,
      autoHideMenuBar: true,
      ...(icon && { icon }),
      webPreferences: {
        nodeIntegration: false,
        contextIsolation: true,
        preload: join(__dirname, '../preload/index.js'),
        webSecurity: true
      }
    })

    // 加载渲染进程
    if (process.env.NODE_ENV === 'development') {
      this.mainWindow.loadURL('http://localhost:3000')
      this.mainWindow.webContents.openDevTools()
    } else {
      this.mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
    }

    // 窗口准备显示时显示
    this.mainWindow.once('ready-to-show', () => {
      // 确保窗口使用配置的大小
      this.mainWindow?.setSize(MAIN_WINDOW_CONFIG.width, MAIN_WINDOW_CONFIG.height)
      this.mainWindow?.center()
      this.mainWindow?.show()
      logger.info('主窗口已显示')
    })

    // 窗口关闭事件
    this.mainWindow.on('closed', () => {
      this.mainWindow = null
      logger.info('主窗口已关闭')
    })

    // 处理外部链接
    this.mainWindow.webContents.setWindowOpenHandler(({ url }) => {
      shell.openExternal(url)
      return { action: 'deny' }
    })

    logger.info('主窗口已创建')
    return this.mainWindow
  }

  /**
   * 创建登录窗口
   */
  createLoginWindow(): BrowserWindow {
    if (this.loginWindow && !this.loginWindow.isDestroyed()) {
      this.loginWindow.focus()
      return this.loginWindow
    }

    this.loginWindow = new BrowserWindow({
      width: LOGIN_WINDOW_CONFIG.width,
      height: LOGIN_WINDOW_CONFIG.height,
      minWidth: LOGIN_WINDOW_CONFIG.minWidth,
      minHeight: LOGIN_WINDOW_CONFIG.minHeight,
      show: false,
      modal: true,
      ...(this.mainWindow && { parent: this.mainWindow }),
      autoHideMenuBar: true,
      webPreferences: {
        nodeIntegration: false,
        contextIsolation: true,
        webSecurity: true,
        // 使用独立的session避免污染主应用
        partition: 'persist:weibo-login'
      }
    })

    // 窗口准备显示时显示
    this.loginWindow.once('ready-to-show', () => {
      this.loginWindow?.show()
      logger.info('登录窗口已显示')
    })

    // 窗口关闭事件
    this.loginWindow.on('closed', () => {
      this.loginWindow = null
      logger.info('登录窗口已关闭')
    })

    logger.info('登录窗口已创建')
    return this.loginWindow
  }

  /**
   * 获取主窗口
   */
  getMainWindow(): BrowserWindow | null {
    return this.mainWindow
  }

  /**
   * 获取登录窗口
   */
  getLoginWindow(): BrowserWindow | null {
    return this.loginWindow
  }

  /**
   * 关闭登录窗口
   */
  closeLoginWindow(): void {
    if (this.loginWindow && !this.loginWindow.isDestroyed()) {
      this.loginWindow.close()
    }
  }

  /**
   * 获取应用图标路径
   */
  private getAppIcon(): string | undefined {
    // 根据平台返回不同的图标
    if (process.platform === 'win32') {
      return join(__dirname, '../../assets/icon.ico')
    } else if (process.platform === 'darwin') {
      return join(__dirname, '../../assets/icon.icns')
    } else {
      return join(__dirname, '../../assets/icon.png')
    }
  }

  /**
   * 显示主窗口
   */
  showMainWindow(): void {
    if (this.mainWindow) {
      if (this.mainWindow.isMinimized()) {
        this.mainWindow.restore()
      }
      this.mainWindow.show()
      this.mainWindow.focus()
    }
  }

  /**
   * 隐藏主窗口
   */
  hideMainWindow(): void {
    if (this.mainWindow) {
      this.mainWindow.hide()
    }
  }

  /**
   * 关闭所有窗口
   */
  closeAllWindows(): void {
    if (this.loginWindow && !this.loginWindow.isDestroyed()) {
      this.loginWindow.close()
      this.loginWindow = null
    }

    if (this.mainWindow && !this.mainWindow.isDestroyed()) {
      this.mainWindow.close()
      this.mainWindow = null
    }
  }
}
